package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Department;
import cn.wolfcode.domain.Permission;
import cn.wolfcode.domain.Role;
import cn.wolfcode.mapper.PermissionMapper;
import cn.wolfcode.mapper.RoleMapper;
import cn.wolfcode.queryobject.QueryObject;
import cn.wolfcode.resultpage.ResultPage;
import cn.wolfcode.service.IRoleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

@Service
public class RoleServiceImpl implements IRoleService {
    // mapper接口实现类对象
    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private PermissionMapper permission;

    @Override
    public void delete(Long id) {
        // 删除关系
        roleMapper.deleteRelation(id);

        // 调用DAO层接口方法
        roleMapper.delete(id);
    }

    @Override
    public void insert(Role role, Long[] ids) {
        // 调用DAO层接口方法
        roleMapper.insert(role);

        if (ids != null && ids.length > 0) {
            // 处理中间表
            for (Long permissionId : ids) {
                roleMapper.insertRelation(role.getId(), permissionId);
            }

        }
    }

    @Override
    public Role selectOne(Long id) {
        // 调用DAO层接口方法
        return roleMapper.selectOne(id);
    }

    @Override
    public List<Role> listAll() {
        // 调用DAO层接口方法
        return roleMapper.selectAll();
    }

    @Override
    public void update(Role role, Long[] ids) {
        // 调用DAO层接口方法
        roleMapper.update(role);

        if (ids != null && ids.length > 0) {
            // 处理中间表
            for (Long permissionId : ids) {
                roleMapper.insertRelation(role.getId(), permissionId);
            }

        }
    }

    /*// service接口查询方法query
    public ResultPage<Role> query(QueryObject qo) {
        // 调用DAO层接口方法,查询数据总条数
        int totalCount = roleMapper.queryForCount(qo);
        if (totalCount == 0){
            // ResultPage.emtry(qo.getPageSize());
            // 空集合,不是null,是这个集合长度为0, 里面没有元素
            return new ResultPage<>(qo.getCurrentPage(),qo.getPageSize(),totalCount, Collections.emptyList());
        }
        // 调用DAO层接口方法,查询当前页面的结果集数据
        List<Role> listData = roleMapper.queryForList(qo);
        return new ResultPage<>(qo.getCurrentPage(),qo.getPageSize(),totalCount,listData);
    }*/

    public PageInfo<Role> query(QueryObject qo) {
        // 使用分页插件,传入当前页,每页显示数量
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
        List<Role> dataList = roleMapper.queryForList(qo);
        return new PageInfo(dataList);
    }
}

